import React from 'react';
import { Table } from 'antd';
import { connect } from 'dva';
import isObject from 'lodash/isObject';
import isEmpty from 'lodash/isEmpty';
import isString from 'lodash/isString';
import sortBy from 'lodash/sortBy';
import ValueDisplay from './valueDisplay';

type messageDisplayProps = {
  vehicleInfoQuery: any;
  record: any;
  messageEncodingDict: any;
};

type MessageEncodingItem = {
  dictValue: string,
  dictKey: string,
  dictDesc: string,
}

const checkStrArr = (value: any[]) =>
  Array.isArray(value) && value.length > 0 && value.every(item => isString(item));
const isExpandable = (value: any) => isObject(value) && !isEmpty(value);
const renderTable = (record, value: Object, columns, messageEncodingDict: { [key: string]: MessageEncodingItem }, tableIndex: number) => {
  const dataSource = Object.keys(value).reduce((acc, key, index) => {
    const { dictValue, dictDesc }: MessageEncodingItem =
      // 下层级的分隔符需要以上层级的分隔符开头，例如 7E10-7D03-7C01 下层级都是以 7E10-7D03-7C01开头，例如 7E10-7D03-7C01-8
      record.splitter && messageEncodingDict[key] && messageEncodingDict[key].dictValue.startsWith(record.splitter)
        ? messageEncodingDict[key]
        : {
            dictValue: '',
            dictKey: key,
            dictDesc: '',
          };
    acc.push({
      tableIndex,
      index,
      splitter: dictValue,
      field: key,
      chinese: dictDesc,
      value: value[key],
    });
    return acc;
  }, []);

  const tableProps = {
    rowKey: record => record.index, // key
    columns,
    dataSource: sortBy(dataSource, row => row.splitter),
    pagination: false as false,
    expandable: {
      expandedRowRender: record => {
        return <MessageDisplay record={record} messageEncodingDict={messageEncodingDict} />;
      },
      rowExpandable: record => {
        return isExpandable(record.value);
      },
    },
  };
  return <Table style={{ margin: '10px' }} bordered {...tableProps} />;
};
const MessageDisplay: React.FC<messageDisplayProps> = props => {
  const { record, messageEncodingDict } = props;
  const { value } = record;

  const isStrArr = checkStrArr(value);

  if (isStrArr) {
    const tableProps = {
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
        },
        {
          title: '值',
          dataIndex: 'value',
          render: (value: number | string | undefined) => {
            return <ValueDisplay value={value} />;
          },
        },
      ],
      dataSource: sortBy(value, row => row.splitter).map((str, index) => ({
        index: index + 1,
        value: str,
      })),
      pagination: false,
    };

    return <Table style={{ margin: '10px' }} {...tableProps} />;
  }

  const tables = Array.isArray(value) ? value : [value];

  const columns = [
    {
      title: '分隔符',
      dataIndex: 'splitter',
    },
    {
      title: '字段',
      dataIndex: 'field',
    },
    {
      title: '中文名称',
      dataIndex: 'chinese',
    },
    Table.EXPAND_COLUMN,
    {
      title: '值',
      dataIndex: 'value',
      width: 400,
      render: value => {
        if (isExpandable(value)) {
          return '';
        }

        const displayValue = isObject(value) ? JSON.stringify(value) : value;
        return (
          <div style={{ maxWidth: '400px' }}>
            <ValueDisplay value={displayValue} />
          </div>
        );
      },
    },
  ];

  if (tables.length > 1) {
    columns.unshift({
      title: '序号',
      width: 50,
      dataIndex: 'tableIndex',
    });
  }

  return (
    <>
      {tables.map((table, tableIndex) =>
        renderTable(record, table, columns, messageEncodingDict, tableIndex + 1),
      )}
    </>
  );
};

export default connect(({ vehicleInfoQuery }) => ({
  vehicleInfoQuery,
}))(MessageDisplay);
